package admin

import (
	"baokaobang/datasourse"
	"baokaobang/models"
	"baokaobang/utils"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
)

type Feedback struct {
	Ctx iris.Context
}

type FeedbackListParam struct {
	PerPage int `json:"perPage"`
	CurPage int `json:"curPage"`
}

func (c *Feedback) OptionsList() mvc.Response {
	return mvc.Response{
		Code: 204,
	}
}

func (c *Feedback) PostList() interface{} {
	feedbackListParam := FeedbackListParam{}
	content, err := c.Ctx.GetBody()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("接收请求参数出错:%s", err.Error()), "")
	}
	err = json.Unmarshal(content, &feedbackListParam)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("解析请求参数出错:%s", err.Error()), "")
	}

	db, err := datasourse.NewMasterOrm()
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法连接数据库:%s", err.Error()), "")
	}

	start := (feedbackListParam.CurPage - 1) * feedbackListParam.PerPage
	feedbackList := make([]models.FeedbackObj, 0)
	err = db.Table("feedback").Alias("f").
		Join("INNER", []string{"user", "u"}, "f.user_id = u.id").Desc("f.id").
		Select("f.*,u.*").Limit(feedbackListParam.PerPage, start).Find(&feedbackList)
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取用户反馈列表:%s", err.Error()), "")
	}

	total, err := db.Where("id > ?", 0).Count(new(models.Feedback))
	if err != nil {
		return utils.CommonRes(1000, fmt.Sprintf("无法获取用户反馈列表:%s", err.Error()), "")
	}

	for i, item := range feedbackList {
		feedbackList[i].Feedback.FeedbackCreated = item.Feedback.Created.Format("2006-01-02 15:04")
	}

	data := map[string]interface{}{
		"total": total,
		"list":  feedbackList,
	}

	return utils.CommonRes(20000, "成功获取用户反馈列表", data)
}
